<template>
    <!-- 头部按钮 -->
    <el-form-item style="width: 188px;">
      <el-select v-model="form.region" placeholder="选择才能看哦" @change="handleSelectChange">
        <el-option v-for="item in cellOptions" :key="item.cellId" :label="item.cellName" :value="item.cellName" />
      </el-select>
    </el-form-item>
    <el-row>
      <el-button type="primary" @click="add()" style="margin-left: 200px; margin-top: -50px;">添加车位</el-button>
        <el-button type="success" disabled style="margin-top: -50px;">必须选择小区才可进行操作</el-button>
    </el-row>
  <el-row>
    <!-- 表格 -->
    <el-table :data="filterTableData" style="width: 100%" >
      <el-table-column label="车位编号" prop="pId" />
      <el-table-column label="所属小区" prop="cellName" />
      <el-table-column label="车位信息" prop="pName" />
      <el-table-column label="创建时间" prop="pCreateTime" >
        <template v-slot="{ row }">
        {{formatDate(row.pCreateTime)}}
        </template>
      </el-table-column>
      <el-table-column label="所属用户" prop="pUserId" />
      <el-table-column label="到期时间" prop="pUseTime" >
      <template v-slot="{ row }">
        {{formatDate(row.pUseTime)}}
        </template>
      </el-table-column>
      <el-table-column label="车位性质" prop="pUseState">
       <template #default="{ row }">
         <span v-if="row.pUseState === 0">已被租</span>
         <span v-else-if="row.pUseState === 1">已被买</span>
         <span v-else>未租未买</span>
       </template>
      </el-table-column>
      <el-table-column label="车位状态" prop="pState">
      <template #default="{ row }">
        <span v-if="row.pState === 0">闲置中</span>
        <span v-else-if="row.pState === 1">使用中</span>
       </template>
      </el-table-column>
      <el-table-column align="right">
        <template #default="scope">
          <el-button type="success" plain @click="editData(scope.row)">更新</el-button>
          <el-button type="danger" plain @click="Delete(scope.row.pId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="demo-pagination-block">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[5, 10, 15, 20]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="zongshu"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </el-row>
        <!-- 添加模态框 -->
    <el-dialog v-model="dialogFormVisible" title="添加or编辑" width="500">
      <el-form :model="form">
          <el-form-item label="车位信息" :label-width="formLabelWidth">
           <el-input v-model="form.pName" autocomplete="off" />
        </el-form-item>
        <el-form-item label="创建时间" :label-width="formLabelWidth">
          <el-date-picker style="width: 400px;" v-model="form.pCreateTime" type="datetime" placeholder="选择日期时间" />
        </el-form-item>
        <el-form-item label="所属用户" :label-width="formLabelWidth">
           <el-input v-model="form.pUserId" autocomplete="off" />
        </el-form-item>
        <el-form-item label="到期时间" :label-width="formLabelWidth">
          <el-date-picker style="width: 400px;" v-model="form.pUseTime" type="datetime" placeholder="选择日期时间" />
        </el-form-item>
        <el-form-item label="车位性质" :label-width="formLabelWidth">
           <el-input v-model="form.pUseState" autocomplete="off" placeholder="（0租，1已买，2未租未买）"/>
        </el-form-item>
        <el-form-item label="车位状态" :label-width="formLabelWidth">
           <el-input v-model="form.pState" autocomplete="off" placeholder="（0闲置中，1使用中）"/>
        </el-form-item>
        <el-form-item label="小区名称" :label-width="formLabelWidth">
          <el-select v-model="form.cellId" placeholder="请选择小区" @change="changename">
          <el-option v-for="item in cellOptions" :key="item.cellId" :label="item.cellName" :value="item.cellName" />
      </el-select>
        </el-form-item>
      </el-form>
       <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button type="primary" @click="addData()"> 确认 </el-button>
          </div>
        </template>
        
        </el-dialog>
        <!-- 编辑模态框 -->
    <el-dialog v-model="editDialogVisible" title="添加or编辑" width="500">
          <el-form :model="editForm">
            <el-form-item label="车位信息" :label-width="formLabelWidth">
           <el-input v-model="editForm.pName" autocomplete="off" />
        </el-form-item>
        <el-form-item label="创建时间" :label-width="formLabelWidth">
          <el-date-picker style="width: 400px;" type="datetime" v-model="editForm.pCreateTime"  placeholder="选择日期时间" />
        </el-form-item>
        <el-form-item label="所属用户" :label-width="formLabelWidth">
           <el-input v-model="editForm.pUserId" autocomplete="off" />
        </el-form-item>
        <el-form-item label="到期时间" :label-width="formLabelWidth">
          <el-date-picker style="width: 400px;" v-model="editForm.pUseTime" type="datetime" placeholder="选择日期时间" />
        </el-form-item>
        <el-form-item label="车位性质" :label-width="formLabelWidth">
           <el-input v-model="editForm.pUseState" autocomplete="off" placeholder="（0租，1已买，2未租未买）"/>
        </el-form-item>
        <el-form-item label="车位状态" :label-width="formLabelWidth">
           <el-input v-model="editForm.pState" autocomplete="off" placeholder="（0闲置中，1使用中）"/>
        </el-form-item>
          </el-form>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="closeEditDialog">关闭</el-button>
              <el-button type="primary" @click="updateData()">保存</el-button>
            </span>
          </template>
        </el-dialog>
  </template>
  <script setup>
  import { ref, reactive, onMounted, toRaw } from "vue";
  import { ElMessage } from "element-plus";
  import axios from "axios";
  const zongshu = ref(0);
  // 当前页码
  const currentPage = ref(1);
  //当前页数量
  const pageSize = ref(5);
  //查询名称
  const search = ref("");
  const filterTableData = ref([]);
  const cellOptions = ref([]); // 初始化为空数组
  const idd=ref(0) //默认id为0
  const dialogFormVisible = ref(false); //添加模态框默认为空
  const editDialogVisible = ref(false);//编辑模态框默认为空
  const editForm = ref({
    pId: 0,
  pCellId: 0,
  pCreateTime: "",
  pName: "",
  pState: 0,
  pUserId: 0,
  pUseState: 0,
  pUseTime: ""
    });
  const form = ref({
    region: "",
    cellId: ""
  });
  //添加功能
  const addData = () => {
      const selectedCell = cellOptions.value.find((item) => item.cellName === form.value.cellId);
      if (selectedCell) {
          const cellId = selectedCell.cellId;
          // 在发送 POST 请求之前设置数据的 cellId 属性为选中的小区 ID
          form.value.pCellId = cellId;
          // 发起添加数据的请求
          axios
              .post("/api/api/Parking", toRaw(form.value))
              .then((response) => {
                  console.log(response.data);
                  if (response.data === 1) {
                      ElMessage.success("添加成功");
                      dialogFormVisible.value = false; // 关闭对话框
                      cx(); // 刷新页面数据
                  } else {
                      ElMessage.error("添加失败，请重试！");
                  }
              })
              .catch((error) => {
                  console.error(error);
              });
      }
  };
  //编辑功能
  const updateData = () => {
    console.log(idd.value)
    console.log(editForm.value)
      axios.put(`/api/api/Parking?id=${idd.value}`,editForm.value)
        .then(function (response) {
          console.log(response.data);
          if (response.data) {
            ElMessage({
              message: "更新成功",
              type: "success",
            });
            closeEditDialog();
            cx(); // 刷新页面
          } else {
            ElMessage.error("更新失败，请重试！");
          }
        })
  };
  //编辑显示功能
  const editData = (row) => {
    idd.value=row.pId
    editForm.value.pId = row.pId;
    editForm.value.pCellId = row.pCellId;
    editForm.value.pCreateTime= row.pCreateTime;
    editForm.value.pName = row.pName;
    editForm.value.pState = row.pState;
    editForm.value.pUserId = row.pUserId;
    editForm.value.pUseState = row.pUseState;
    editForm.value.pUseTime = row.pUseTime;
    editDialogVisible.value = true;
  };
  //点击关闭按钮
  const closeEditDialog = () => {
      editDialogVisible.value = false;
  };
  //删除按钮
  function Delete(pId) {
    console.log(pId)
  axios.delete(`/api/api/Parking?id=${pId}`)
    .then((response) => {
       if (response.status === 200) {
          ElMessage({
            message: "删除成功",
            type: "success",
          });
          dialogFormVisible.value = false;
        } else {
          ElMessage({
            message: "删除失败",
            type: "waring",
          });
        }
        cx()
    })
    .catch((error) => {
      console.error(error.response.data); // 获取服务器返回的详细错误信息
      console.error(error.response.status); // 获取HTTP状态码
      console.error(error.response.statusText); // 获取HTTP状态码对应的文本描述
    });
  }
  //来获取小区选项的数据
  onMounted(() => {getCelloptions();});
    // 获取小区下拉选项
    function getCelloptions() {
    axios
      .get(`/api/api/Property_Information/La`)
      .then((response) => {
        console.log("小区数据：", response.data);
        cellOptions.value = response.data.map(item => ({
          cellId: item.cellId,
          cellName: item.cellName
        }));
      })
      .catch((error) => {
        console.error(error);
      });
    }
    // 分页显示数量发生改变时触发
    function handleSizeChange() {
      cx();
    }
    // 分页码发生改变时触发
    function handleCurrentChange() {
      cx();
    }
    // 查询数据和总条数
    function cx() {
    console.log("页码" + currentPage.value);
    console.log("页数" + pageSize.value);
    const selectedCell = cellOptions.value.find((item) => item.cellName === form.value.region);
    const pCellId = selectedCell ? selectedCell.cellId : -1;
    // 发起 GET 请求
    axios
      .get(
        `/api/api/Parking?ys=${pageSize.value}&ym=${currentPage.value}&name=${search.value}&pCellId=${pCellId}`
      )
      .then((response) => {
        filterTableData.value = response.data.data;
        zongshu.value = response.data.totalCount;
        console.log(filterTableData.value);
      })
      .catch((error) => {
        console.error(error);
      });
    }
    // 下拉框选择改变时触发
    function handleSelectChange() {
    const selectedCell = cellOptions.value.find((item) => item.cellName === form.value.region);
    const pCellId = selectedCell ? selectedCell.cellId : -1;
    axios
      .get(`/api/api/Parking/GetByCellId?pCellId=${pCellId}`)
      .then((response) => {
        filterTableData.value = response.data.data;
        zongshu.value = response.data.totalCount;
        console.log(filterTableData.value);
      })
      .catch((error) => {
        console.error(error);
      });
    }
    //添加按钮
    function add() {
        form.value = {        // 在确认添加后清空表单数据
          pRidgepole:"",
          pCount:"",
          pUnitFloor:"",
          pUserId:""
              };
        dialogFormVisible.value = true;
    }
      //转换时间格式
  function formatDate(dateString) {
  const date = new Date(dateString);
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const day = date.getDate();
  return `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`;
}
    </script>
  